package cn.edu.jxau.core.service;

import cn.edu.jxau.core.exception.ServiceException;
import cn.edu.jxau.core.process.spectrumutil.AlgorithmUtils;
import cn.edu.jxau.core.process.spectrumutil.GetSpectrum;
import cn.edu.jxau.core.util.SerializaObject;
import cn.edu.jxau.core.util.StringUtil;
import cn.edu.jxau.core.util.upload.FileUpload;
import cn.edu.jxau.core.vo.Point;
import cn.edu.jxau.core.vo.SpectrumFile;
import cn.edu.jxau.framework.dao.core.Session;
import cn.edu.jxau.framework.dao.core.sqlSessionFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 光谱分析服务
 * <p>
 * MangoDai
 * 2017 08 26 10:22 AM
 */
public class SpectrumAnalysisService extends ServiceSupport {
    private static Logger logger = LoggerFactory.getLogger(SpectrumAnalysisService.class);

    /**
     * 有参构造函数
     *
     * @param view
     * @param params
     * @param data
     */
    public SpectrumAnalysisService(String view, Map<String, Object[]> params, Map<String, Object> data) throws ServiceException {
        super(view, params, data);
        execute(view, params, data);
    }

    public void exportSpectrumImage(Map<String, Object[]> params, Map<String, Object> data) {
        String echartsIMG = getParamStringValue(params, "echartsIMG", 0);
        echartsIMG = echartsIMG.replaceAll(" ","+");
        echartsIMG = echartsIMG.split("base64,")[1];
        String spectrum = getParamStringValue(params, "spectrum", 0);
        String connetcion = getParamStringValue(params, "connetcion", 0);
        if (StringUtil.isBlank(echartsIMG) || StringUtil.isBlank(spectrum) || StringUtil.isBlank(connetcion)) {
            data.put("content", "数据为空");
            data.put("result", FAILED);
            return;
        }
//        System.out.println(JSON.toJSONString(params));
        String raletivePath = FileUpload.IMAGEPATH + StringUtil.getdateConfoundAndUUDI() + ".png";
//        String raletivePath = FileUpload.IMAGEPATH + StringUtil.getdateConfoundAndUUDI();
        File file = new File(FileUpload.getBaseABSPath(), raletivePath);
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        StringUtil.GenerateImage(echartsIMG, file);
    }

    /**
     * 需要光谱文件 预处理算法，分析算法，国标
     * * @Author Mangodai
     *
     * @param params
     * @param data
     * @Date 9/3/2017 9:38 AM
     */

    public void spectrumAnalysis(Map<String, Object[]> params, Map<String, Object> data) throws IllegalAccessException, IOException, InstantiationException {
        String spectrumID = getParamStringValue(params, "spectrumID", 0);
        String standardSpectrumID = getParamStringValue(params, "standardSpectrumID", 0);
        String pretreatmentID = getParamStringValue(params, "pretreatmentID", 0);
        String analysisID = getParamStringValue(params, "analysisID", 0);
//        String
        if (!StringUtil.isBlank(spectrumID) && !StringUtil.isBlank(pretreatmentID) && !StringUtil.isBlank(analysisID)) {
            Map<String, Object> param = new HashMap<>(); //用来封装传递给数据库的参数
            List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的
            try {
                getConnectionData(spectrumID, pretreatmentID, analysisID, param, datas);
                String path = datas.get(0).get("spectrumFileUrl").toString();
                File file = new File(FileUpload.getBaseABSPath(), path);
                SpectrumFile parcelagle = GetSpectrum.parcelagle(file);
                String pretreatmentAlgorithm = datas.get(1).get("algorithmRealPath").toString();
                String analysisAlgorithm = datas.get(2).get("algorithmRealPath").toString();
                JSONArray prementSpectrum = AlgorithmUtils.useJar2PrementSpectrum(pretreatmentAlgorithm, parcelagle, false);
//                logger.debug(JSON.toJSONString(prementSpectrum, SerializerFeature.PrettyFormat));
                List<Point> points = getPoints(prementSpectrum);
                parcelagle.setPoints(points);
                JSONArray result = AlgorithmUtils.useJar2PrementSpectrum(analysisAlgorithm, parcelagle, true);
//                logger.debug(JSON.toJSONString(result, SerializerFeature.PrettyFormat));
                parcelagle.flush();
                SerializaObject.writeObject(parcelagle, file.getParent());
                data.put("spectrumFile", parcelagle);
                data.put("spectrumID", spectrumID);
                data.put("result", SUCCESS);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
    }

    private List<Point> getPoints(JSONArray prementSpectrum) {
        List<Point> points = new ArrayList<>(prementSpectrum.size());
        prementSpectrum.forEach(i -> {
            JSONObject jo = (JSONObject) i;
            Point point = new Point(jo.getDoubleValue("x"), jo.getDoubleValue("y"));
            points.add(point);
        });
        return points;
    }

    /**
     * 从检验线相应数据，得到对应的对象和数据
     *
     * @param spectrumID
     * @param pretreatmentID
     * @param analysisID
     * @param param
     * @param datas
     * @throws ClassNotFoundException
     * @throws DocumentException
     */
    private void getConnectionData(String spectrumID, String pretreatmentID, String analysisID, Map<String, Object> param, List<HashMap<String, Object>> datas) throws ClassNotFoundException, DocumentException {
        Session session = sqlSessionFactory.getInstance().getSession();
        param.put("spectrumID", spectrumID);
        session.execute("wfpquerySpectrum", param, datas);
        param.clear();
        param.put("algorithmID", pretreatmentID);
        param.put("isDelete", 0);
        session.execute("wfpqueryAlgorithm", param, datas);
        param.clear();
        param.put("algorithmID", analysisID);
        param.put("isDelete", 0);
        session.execute("wfpqueryAlgorithm", param, datas);
    }

}
